<template>
  <div>
    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0">
            <el-form-item label="上级部门" prop="parentId">
              <treeselect v-model="parentRenderKey" :options="deptOptions" :normalizer="normalizer" placeholder="选择上级部门"
                :multiple="true" :autoSelectDescendants="false" :flat="true" @input="handleParentIdChange" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="负责人" prop="email">
              <el-select v-model="form.leader" filterable remote reserve-keyword clearable placeholder="请选择负责人"
                :remote-method="searchUser" style="width: 100%" @clear="clearUser">
                <el-option v-for="item in userOptions" :key="item.userId" :label="item.nickName" :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{
                dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="部门类型" prop="email">
              <el-select v-model="form.deptType" placeholder="请选择部门类型" style="width: 100%">
                <el-option v-for="dict in dict.type.sys_dept_type_dict" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="close">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import dialogMixin from '@/mixins/dialogMixin.js';
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import * as DeptApi from "@/api/system/dept";
const localCache = require("@/plugins/cache").default.local;
import * as UserApi from "@/api/system/user";

export default {
  name: 'DeptEditDialog',
  dicts: ["sys_normal_disable", "sys_dept_type_dict", "org_type_dict"],
  mixins: [dialogMixin],
  components: { Treeselect },
  data() {
    return {
      title: '',
      // 部门树选项
      deptOptions: [],
      form: {},
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "上级部门不能为空", trigger: "blur" },
        ],
        deptName: [
          { required: true, message: "部门名称不能为空", trigger: "blur" },
        ],
        orderNum: [
          { required: true, message: "显示排序不能为空", trigger: "blur" },
        ]
      },
      renderKeyDict: [],
      parentRenderKey: [],
      userOptions: []
    }
  },
  methods: {
    handleAdd() {
      this.reset();
      this.title = "添加部门";
      DeptApi.treeselect().then((response) => {
        this.deptOptions = this.makeRenderKey(response.data);
      });
      this.open = true;
    },
    handleUpdate(deptId) {
      this.reset();
      DeptApi.treeselect().then((response) => {
        this.deptOptions = this.makeRenderKey(response.data);
        DeptApi.getDept(deptId).then((response) => {
          let parentIds = response.data.parentId.split(',');
          response.data.parentId = parentIds;
          let parentRenderKey = [];
          parentIds.forEach(p => {
            let dict = this.renderKeyDict.find(val => val.deptId == p);
            parentRenderKey.push(dict.renderKey);
          });
          this.parentRenderKey = parentRenderKey;
          this.form = response.data;
          this.open = true;
          this.title = "修改部门";
        });
      });
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: undefined,
        parentId: undefined,
        deptName: undefined,
        orderNum: undefined,
        leader: undefined,
        phone: undefined,
        email: undefined,
        status: "0",
      };
      this.parentRenderKey = [];
      this.resetForm("form");
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.renderKey,
        label: node.deptName,
        children: node.children,
      };
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        let data = Object.assign({}, this.form);
        data.parentId = data.parentId.join(',');
        if (valid) {
          if (data.deptId != undefined) {
            DeptApi.updateDept(data).then((response) => {
              localCache.remove("deptData");
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              // this.getList();
              this.$emit('handleOk');
            });
          } else {
            DeptApi.addDept(data).then((response) => {
              localCache.remove("deptData");
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              // this.getList();
              this.$emit('handleOk');
            });
          }
        }
      });
    },
    handleParentIdChange(value, instanceId) {
      let parentId = [];
      this.parentRenderKey.forEach(k => {
        let dict = this.renderKeyDict.find(val => val.renderKey == k);
        parentId.push(dict.deptId);
      });
      this.form.parentId = parentId;
    },
    makeRenderKey(data) {
      data.forEach(item => {
        item.renderKey = String(item.deptId);
        this.renderKeyDict.push({ renderKey: item.renderKey, deptId: item.deptId });
        if (item.children.length > 0) {
          let res = this.makeChildRenderKey(item.children, item.renderKey);
          item.children = res;
        }
      });
      return data;
    },
    makeChildRenderKey(item, renderKey) {
      item.forEach(i => {
        i.renderKey = `${renderKey}-${i.deptId}`;
        this.renderKeyDict.push({ renderKey: i.renderKey, deptId: i.deptId });
        if (i.children.length > 0) {
          let res = this.makeChildRenderKey(i.children, i.renderKey);
          i.children = res;
        }
      });
      return item;
    },
    searchUser(query) {
      UserApi.listUserNoPage({ nickName: query }).then(res => {
        this.userOptions = res.data;
      })
    },
    clearUser() {
      this.userOptions = [];
    }
  }
}
</script>
<style lang="scss" scoped>

</style>